<template>
  <div>NewsItem</div>
  <p>{{ title }}--{{ id }}</p>
  <!-- <p>{{ route.query.title }}--{{ route.query.id }}</p> -->
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "NewsItem",
});
</script>

<script setup lang="ts">
import { useRoute, onBeforeRouteUpdate } from "vue-router";
import { toRefs, watch, computed } from "vue";
const route = useRoute();
//1.直接解构数据会出现无法监听到动态路由的改变
// const { title, id } = route.query;
//2.在模板中直接使用route.query.xxx获取 即可监听到route的改变

//3.使用toRefs,还是无法实现监听动态切换,因为没有监听到route的改变
// const { title, id } = toRefs(route.query);

//4.使用watch来监听route的改变,但是内部重新赋值的时候不能使用解构语法
/* const { title, id } = toRefs(route.query);
watch(route, () => {
  title.value = route.query.title;
  id.value = route.query.id;
}); */

//5. 使用组件内更新守卫 来完成监听route的改变
/* const { title, id } = toRefs(route.query);
onBeforeRouteUpdate(() => {
  title.value = route.query.title;
  id.value = route.query.id;
}); */

//6. 我们一般拿动态路由route中的值的时候,直接使用计算属性来拿即可
const title = computed(() => {
  return route.query.title;
});
const id = computed(() => {
  return route.query.id;
});
</script>

<style scoped></style>
